/*
 * test_http_c.cpp
 *
 *  Created on: Dec 11, 2013
 *      Author: killerg
 */


#include "share/http_c3.h"
#include "share/json/json.h"
#include "share/http_c2.h"
#include "share/http_c.h"
#include "share/util.h"
#include <string>
#include <assert.h>


static int s_fail = 0;
static int s_ok = 0;
static int s_doing = 0;
static int s_cur = 0;

static bool test_http_c(const char* host, int num, int chunk) {
    http_client3 cli;

    if (!cli.init()) {
        perror("http_client2::init error");
        return false;
    }

    s_cur = 0;
    Json::Value json;
    while ((s_ok + s_fail) < num) {
    	while (s_cur < num && s_doing < chunk) {
            json["index"] = s_cur++;
            std::string url = fmt_cstr("http://%s:9999/killerg/haha", host);
            bool res = cli.do_query(url.c_str(), NULL, [](CURLcode err, const std::string& data){
            	--s_doing;
                if (err != CURLE_OK) {
                	++s_fail;
                } else {
                	++s_ok;
                }
            });
            if (res) {
            	++s_doing;
            }
    	}
    	cli.update();
    }


    cli.destroy();
    assert(s_doing == 0);

    printf("num:%d ok:%d fail:%d\n", num, s_ok, s_fail);

    return true;
}

extern bool test_http_s(int fps);

bool test_http_cs(int argc, char** argv) {
    if (argc < 2) {
        printf("usage: test s fps\n");
        printf("usage: test c host num chunk\n");
        return false;
    }

    if (argv[1][0] == 'c') {
        int chunk = 100;
        if (argc == 5)
            chunk = atoi(argv[4]);
        test_http_c(argv[2], atoi(argv[3]), chunk);
    } else if (argv[1][0] == 's') {
        int fps = 100;
        if (argc == 3)
            fps = atoi(argv[2]);
        test_http_s(fps);
    }

    return true;
}
